<template>
  <el-card class="chart-card">
    <template #header>
      <div class="card-header">
        <span>历史价格趋势</span>
        <el-select v-model="materialValue" placeholder="选择物料" size="small">
          <el-option v-for="item in materialOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
    </template>
    <div ref="chartContainer" class="chart-container" style="height:350px;"></div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ChartResizer } from '../../utils/chartResize'

// 定义类型
interface Supplier {
  id: string;
  name: string;
  level: string;
}

// 定义props
const props = defineProps<{
  selectedMaterial: string;
  suppliers: Supplier[];
}>()

// 定义emit
const emit = defineEmits(['update:selectedMaterial', 'chart-ready'])

// 物料选项数据
const materialOptions = [
  { value: 'M001', label: '钢板Q235' },
  { value: 'M002', label: '铝合金板6061' },
  { value: 'M003', label: '紫铜棒T2' },
  { value: 'M004', label: '橡胶垫片' },
  { value: 'M005', label: '轴承SKF6204' }
]

// 保持内部状态与外部同步
const materialValue = ref(props.selectedMaterial)

// 监听内部状态变化并通知父组件
watch(materialValue, (newValue) => {
  emit('update:selectedMaterial', newValue)
  updateChart()
})

// 监听外部属性变化
watch(() => props.selectedMaterial, (newValue) => {
  materialValue.value = newValue
})

// 图表实例
let chart: echarts.ECharts | null = null
const chartContainer = ref<HTMLElement | null>(null)

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  
  // 改用递归方式尝试初始化，设置最大重试次数
  tryInitChart(1, 10) // 从第1次开始，最多尝试10次
}

// 尝试初始化图表，使用计数器和最大重试次数
const tryInitChart = (attempt: number, maxRetries: number) => {
  if (!chartContainer.value) return
  
  // 检查容器尺寸
  const rect = chartContainer.value.getBoundingClientRect()
  console.log(`PriceTrendChart容器尺寸(尝试${attempt}/${maxRetries}):`, rect.width, rect.height)
  
  if (rect.width <= 5 || rect.height <= 5) {
    if (attempt < maxRetries) {
      console.warn(`PriceTrendChart容器尺寸无效, 延迟重试 ${attempt}/${maxRetries}`)
      // 延迟时间随着重试次数增加
      const delay = Math.min(200 * attempt, 1000) // 最长延迟1秒
      setTimeout(() => tryInitChart(attempt + 1, maxRetries), delay)
    } else {
      // 最大尝试次数后强制初始化
      console.warn('达到最大重试次数，强制初始化图表')
      forceInitChart()
    }
    return
  }
  
  // 正常初始化
  initChartInstance()
}

// 强制初始化图表实例，即使容器尺寸不理想
const forceInitChart = () => {
  if (!chartContainer.value) return
  
  // 确保容器有最小尺寸
  chartContainer.value.style.height = '350px'
  chartContainer.value.style.width = '100%'
  
  console.log('PriceTrendChart强制初始化图表')
  initChartInstance()
}

// 实际初始化图表实例的共用方法
const initChartInstance = () => {
  if (!chartContainer.value) return
  
  // 如果已经初始化过，先销毁
  if (chart) {
    chart.dispose()
  }
  
  console.log('PriceTrendChart开始初始化图表')
  // 初始化图表
  chart = echarts.init(chartContainer.value)
  
  // 注册到ChartResizer
  ChartResizer.getInstance().register('priceTrendChart', chart, chartContainer.value)
  
  // 更新图表
  updateChart()
  
  // 通知父组件图表已就绪
  emit('chart-ready', 'priceTrendChart')
}

// 更新图表
const updateChart = () => {
  if (!chart) return
  
  // 模拟历史价格数据
  const dates = ['2023-01', '2023-02', '2023-03', '2023-04', '2023-05', '2023-06']
  const seriesData = [
    {
      name: '供应商A',
      type: 'line',
      data: [320, 332, 325, 340, 335, 320]
    },
    {
      name: '供应商B',
      type: 'line',
      data: [350, 345, 355, 365, 360, 350]
    },
    {
      name: '供应商C',
      type: 'line',
      data: [335, 330, 340, 350, 345, 335]
    },
    {
      name: '市场平均价',
      type: 'line',
      lineStyle: {
        type: 'dashed'
      },
      data: [335, 336, 340, 352, 347, 335]
    }
  ]
  
  // 获取容器宽度以设置响应式配置
  const containerWidth = chart.getWidth()
  const isSmallScreen = containerWidth < 500
  
  // 设置图表配置
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: [...props.suppliers.map(supplier => supplier.name), '市场平均价'],
      type: isSmallScreen ? 'scroll' : 'plain',
      textStyle: {
        fontSize: isSmallScreen ? 10 : 12
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: {
        fontSize: isSmallScreen ? 10 : 12
      }
    },
    yAxis: {
      type: 'value',
      name: '价格(元)',
      nameTextStyle: {
        fontSize: isSmallScreen ? 10 : 12
      },
      axisLabel: {
        fontSize: isSmallScreen ? 10 : 12
      }
    },
    series: seriesData
  }
  
  chart.setOption(option)
}

// 组件挂载
onMounted(() => {
  // 确保在下一个渲染周期执行，并且使用更长的延时以确保DOM完全渲染
  setTimeout(() => {
    initChart()
  }, 500)
  
  // 监听窗口大小变化，重新渲染图表
  window.addEventListener('resize', handleResize)
})

// 组件卸载前清理资源
onBeforeUnmount(() => {
  if (chart) {
    ChartResizer.getInstance().unregister('priceTrendChart')
    chart.dispose()
  }
  
  // 移除事件监听器
  window.removeEventListener('resize', handleResize)
})

// 处理窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}
</script>

<script lang="ts">
export default {
  name: 'PriceTrendChart'
}
</script>

<style scoped>
.chart-card {
  margin-bottom: 0;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
  position: relative;
  display: block;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .chart-container {
    height: 300px;
  }
}

@media (max-width: 768px) {
  .chart-container {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .chart-container {
    height: 200px;
  }
}
</style> 